package luxing.web.convert;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * 
 * @author zzc
 *
 */
public class DateConvertEditor extends PropertyEditorSupport {

	private static final Logger logger = Logger.getLogger(DateConvertEditor.class);

	private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.isNotBlank(text)) {
			try {
				if (text.indexOf(":") == -1 && text.length() == 10) {
					setValue(this.dateFormat.parse(text));
				} else if (text.indexOf(":") > 0 && text.length() == 19) {
					setValue(this.datetimeFormat.parse(text));
				} else if (text.indexOf(":") > 0 && text.length() == 21) {
					text = text.replace(".0", "");
					setValue(this.datetimeFormat.parse(text));
				} else {
					logger.error("输入时间格式有误");
					throw new IllegalArgumentException("输入时间格式有误");
				}
			} catch (ParseException ex) {
				logger.error("输入时间格式有误");
				IllegalArgumentException iae = new IllegalArgumentException("输入时间格式有误:" + text);
				iae.initCause(ex);
				throw iae;
			}
		} else {
			setValue(null);
		}
	}
}
